package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 用户一直不支付
     */
    @Scheduled(cron = "0 * * * * ? ") // 每分钟一次
    public void processTimeOutOrder(){
        log.info("定时处理超时订单{}", LocalDateTime.now());
        /*
        LocalDateTime.now().plusMinutes(-15)
        为当前时间减十五分钟的意思
        */
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

        // 判断查询出来的订单集合是否为空
        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                // 将超时订单状态设置为已取消
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("用户订单支付超时，自动取消");
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 订单派送完成，但是管理端一直没有点击完成
     */
    @Scheduled(cron = "0 0 1 * * ? ") // 每天凌晨1点时触发
    public void processDeliveryOrder(){
        log.info("定时处理派送中订单{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        // 判断查询出来的订单结合是否为空
        if(ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                // 将一直没有点击完成的订单设置成已完成
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
